﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace GoodStuff.GSAdmin
{
    public static class Program
    {
        public static int Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Specify command name");
                    return 100;
                }

                switch (args[0])
                {
                    case "mergeConfig":
                        PerformMerge("web.config", "transform.config");
                        break;
                }

                return 0;
            }
            catch (Exception ee)
            {
                Console.WriteLine(ee.Message);
                return 100;
            }
        }

        private static void PerformMerge(string webConfig, string transformFile)
        {
            //create a backup of the original file.
            System.IO.File.Copy(webConfig, "web_pretransform.config", true);

            //load the xml document.
            XmlDocument sourceDoc = new XmlDocument();
            //sourceDoc.PreserveWhitespace = true;
            sourceDoc.Load(webConfig);

            XmlDocument transformDoc = new XmlDocument();
            //transformDoc.PreserveWhitespace = true;
            transformDoc.Load(transformFile);

            Xml.XmlMerger merge = new Xml.XmlMerger(sourceDoc.DocumentElement);
            merge.ApplyMerge(transformDoc.DocumentElement, null);

            //Completely format the output document.
            XmlWriterSettings settings = new XmlWriterSettings()
            {
                Indent = true,
                IndentChars = @"   ",
                ConformanceLevel = System.Xml.ConformanceLevel.Document,
                NewLineOnAttributes = false,
                NewLineChars = Environment.NewLine,
                NewLineHandling = NewLineHandling.Replace
            };
            //sourceDoc.PreserveWhitespace = false;
            using (XmlWriter writer = XmlWriter.Create(webConfig, settings))
            {
                sourceDoc.Save(writer);
            }
        }
    }
}
